import json

from django.http import HttpResponse
from requests import Response
from rest_framework import status
from rest_framework.exceptions import NotFound
from rest_framework.generics import GenericAPIView

from rest_api.utils.lucky_sport_pagination import LuckyScportPagination


class EmptyPageListViewMixin(object):
    """
    List a queryset.
    """

    def list(self, request, *args, **kwargs):
        queryset = self.filter_queryset(self.get_queryset())
        try:
            page = self.paginate_queryset(queryset)
        except NotFound:
            _dict = {}
            _dict['pageNo'] = 0
            _dict['pageSize'] = 0
            _dict['total'] = 0
            _dict['next'] = 0
            _dict['previous'] = 0
            _dict['list'] = []
            return HttpResponse(json.dumps(_dict), status=status.HTTP_200_OK, content_type='applicaton/json')

        if page is not None:
            serializer = self.get_serializer(page, many=True)
            return self.get_paginated_response(serializer.data)

        serializer = self.get_serializer(queryset, many=True)
        return Response(serializer.data)


class PageListView(EmptyPageListViewMixin,
                   GenericAPIView):
    """
   Concrete view for listing a queryset.
   """
    pagination_class = LuckyScportPagination

    def get(self, request, *args, **kwargs):
        return self.list(request, *args, **kwargs)
